package com.nulldev.util.web.HttpServer3.extensions.websocket;

import java.util.Collection;

import com.nulldev.util.VariableAPI.StringsUtil;
import com.nulldev.util.data.Variables;
import com.nulldev.util.web.HttpServer3.extensions.websocket.peers.PeerManager;
import com.nulldev.util.web.HttpServer3.extensions.websocket.util.CloseReason;

public abstract class WebSocketPage implements IWebSocketPage {

	private final String protocol_name;
	private final String id;
	private final PeerManager peerManager = new PeerManager();
	private final boolean prefersLowLatency;

	public WebSocketPage(final String id) {
		this(id, null, false);
	}

	public WebSocketPage(final String id, final String protocol_name) {
		this(id, protocol_name, false);
	}

	public WebSocketPage(final String id, final String protocol_name, final boolean preferLowLatency) {
		Variables.requireNonNull(id, "id");
		this.protocol_name = protocol_name;
		this.prefersLowLatency = preferLowLatency;
		if (!id.startsWith("/")) {
			this.id = "/" + id.replaceAll(" ", "%20");
		} else
			this.id = id.replaceAll(" ", "%20");
	}

	@Override
	public String getID() {
		return this.id;
	}

	@Override
	public boolean prefersLowLatency() {
		return this.prefersLowLatency;
	}

	@Override
	public void onPeerConnect(final Peer peer) {
		this.peerManager.registerPeer(peer);
		this.peerConnected(peer);
	}

	public abstract void peerConnected(final Peer peer);

	@Override
	public void onPeerClose(final Peer peer, final CloseReason reason) {
		this.peerManager.removePeer(peer);
		this.peerDisconnected(peer);
	}

	public Collection<Peer> clients() {
		return this.peerManager.clients();
	}

	public boolean isExcludedFromCaptcha() {
		return true;
	}

	public abstract void peerDisconnected(final Peer peer);

	@Override
	public boolean hasProtocolName() {
		return !StringsUtil.isBlank(this.protocol_name);
	}

	@Override
	public String getProtocolName() {
		return this.protocol_name;
	}
}
